<script>
import { ref } from 'vue'
import LogicFlow from '@logicflow/core'
import { ElMessage } from 'element-plus'
import { BpmnElement, SelectionSelect, DndPanel } from '@logicflow/extension'
import '@logicflow/core/dist/style/index.css'
import '@logicflow/extension/lib/style/index.css'
import { queryFlow, createFlow, saveFlow, deployFlow } from '../service/flow'
import turboAdapter from './turboAdapter'
import Toolbar from './Toolbar.vue'

const CALLER = 'TEST_CALLER'
const TENANT = 'TEST_TENANT'

export default {
  setup() {
    const count = ref(0)
    const flowName = ref('流程')
    const flowKey = ref('')
    const activeData = ref(null)
    const openDrawer = ref(false)
    const drawType = ref('')
    const graphData = ref('')
    return {
      count,
      flowKey,
      flowName,
      activeData,
      openDrawer,
      drawType,
      graphData
    }
  },
  async mounted() {
    let flowModuleId = this.$route.params.flowModelId
    if (!flowModuleId) {
      flowModuleId = await this.createFlow()
    }
    this.flowModuleId = flowModuleId;
    await this.queryFlow()
    this.lf = new LogicFlow({
      container: this.$refs.container,
      grid: {
        visible: true,
        type: 'mesh',
        size: 10,
        config: {
          color: '#eeeeee'
        }
      },
      // adjustEdge: false,
      hoverOutline: false,
      edgeSelectedOutline: false,
      keyboard: {
        enabled: true,
      },
      // keyboard: true,
      plugins: [
        // NodeRedExtension,
        BpmnElement,
        SelectionSelect,
        DndPanel,
        turboAdapter,
      ]
    })
    
    this.lf.extension.dndPanel.setPatternItems([
      {
        label: '选区',
        icon: '',
        callback: () => {
          this.lf.extension.selectionSelect.openSelectionSelect();
          this.lf.once('selection:selected', () => {
            this.lf.extension.selectionSelect.closeSelectionSelect();
          });
        }
      },
      {
        type: 'bpmn:startEvent',
        text: '开始',
        label: '开始节点',
        icon: '',
      },
      {
        type: 'bpmn:userTask',
        label: '用户任务',
        icon: '',
      },
      {
        type: 'bpmn:exclusiveGateway',
        label: '条件判断',
        icon: '',
      },
      {
        type: 'bpmn:endEvent',
        text: '结束',
        label: '结束节点',
        icon: '',
      }
    ]);
    this.lf.render(this.flowModel || {})
    this.lf.on('edge:dbclick', ({ data }) => {
      this.activeData = data
      this.drawType = 'edgeCondition'
      this.openDrawer = true
    })
  },
  methods: {
    async createFlow () {
      return new Promise((resolve) => {
        createFlow({
          caller: CALLER,
          flowKey: "flowKey1",
          flowName: this.flowName,
          tenant: TENANT
        }).then(({ data, errCode }) => {
          if (errCode === 1000) {
            const { flowModuleId } = data;
            resolve(flowModuleId);
          }
        })
      })
    },
    async queryFlow() {
      return new Promise((resolve) => {
        queryFlow({
          flowModuleId: this.flowModuleId,
          // flowModuleId: '611a51d8-b199-11ec-bbbf-bec61a540123',
          // flowDeployId: "836fb274-b19d-11ec-be16-bec61a540123"
        }).then(({ data, errCode }) => {
          if (errCode === 1000) {
            const { flowModel, flowName, flowKey } = data;
            if (flowModel) {
              this.flowModel = JSON.parse(flowModel)
            } else {
              this.flowModel = {}
            }
            this.flowName = flowName
            this.flowKey = flowKey
            resolve()
          }
        }).catch(e => {
          console.log(333, e)
        })
      })
    },
    $_saveFlow () {
      const graphData = this.lf.getGraphData()
      saveFlow({
        caller: "testCaller",
        flowModel: JSON.stringify(graphData),
        flowModuleId: this.flowModuleId,
        tenant: "testTenant",
      }).then(() => {
        ElMessage({
          showClose: true,
          message: '保存成功',
          type: 'success',
        })
      })
    },
    $_publishFlow () {
      deployFlow({
        caller: "testCaller",
        flowModuleId: this.flowModuleId,
        tenant: "testTenant",
      }).then(({ errMsg, errCode }) => {
        if (errCode !== 1000) {
          ElMessage({
            showClose: true,
            message: errMsg,
            type: 'error',
          })
        } else {
          ElMessage({
            showClose: true,
            message: '发布成功',
            type: 'success',
          })
        }
      })
    },
    $_getData () {
      this.openDrawer = true
      this.drawType = 'graphData'
      this.graphData = JSON.stringify(this.lf.getGraphData())
    },
    $_saveCondition () {
      this.lf.setProperties(this.activeData.id, this.activeData.properties)
      this.openDrawer = false
    }
  },
  components: {
    Toolbar
  }
}
</script>

<template>
  <div class="flow-chart">
    <toolbar
      class="node-red-toolbar"
      @saveFlow="$_saveFlow"
      @publishFlow="$_publishFlow"
      @getData="$_getData"
      :flowName="flowName"
      :flowKey="flowKey"
    >
    </toolbar>
    <div ref="container" class="container"></div>
    <el-drawer
      v-model="openDrawer"
      title="查看"
    >
      <div v-if="drawType === 'edgeCondition'">
        <span>判断条件</span>
        <el-input
          v-model="activeData.properties.conditionsequenceflow"
          :rows="2"
          type="textarea"
          placeholder="请输入条件判断表达式"
        />
        <div>名称</div>
        <el-input v-model="activeData.text"></el-input>
        <el-button @click="$_saveCondition">确认</el-button>
      </div>
      <div v-if="drawType === 'graphData'">
        <span>流程图数据</span>
        <el-input
          v-model="graphData"
          :rows="20"
          type="textarea"
          placeholder="请输入条件判断表达式"
        />
      </div>
    </el-drawer>
  </div>
</template>

<style scoped>
.container {
  width: 100%;
  height: 100%;
}
.flow-chart {
  position: relative;
  width: 100%;
  height: 100%;
}

.flow-chart-palette {
  position: absolute;
  left: 0;
  top: 0;
  z-index: 1;
}
.node-red-toolbar {
  position: absolute;
  width: 100%;
  left: 0;
  top: 0;
  z-index: 1;
  background: #fbfbfb;
}
::v-deep .lf-dndpanel {
  top: 30px;
}
</style>
